package com.bletoothutils;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import com.fileutils.StringUtils;
import com.inuker.bluetooth.library.connect.listener.BleConnectStatusListener;
import com.inuker.bluetooth.library.connect.listener.BluetoothStateListener;
import com.inuker.bluetooth.library.connect.options.BleConnectOptions;
import com.inuker.bluetooth.library.connect.response.BleConnectResponse;
import com.inuker.bluetooth.library.connect.response.BleNotifyResponse;
import com.inuker.bluetooth.library.connect.response.BleUnnotifyResponse;
import com.inuker.bluetooth.library.model.BleGattProfile;
import com.inuker.bluetooth.library.receiver.listener.BluetoothBondListener;
import com.inuker.bluetooth.library.search.SearchRequest;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.search.response.SearchResponse;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static com.inuker.bluetooth.library.Constants.REQUEST_SUCCESS;
import static com.inuker.bluetooth.library.Constants.STATUS_CONNECTED;
import static com.inuker.bluetooth.library.Constants.STATUS_DISCONNECTED;

/**
 * Created by Administrator on 2019/6/15.BleToothManager
 */

public class BleToothKitUtil {
    public static final int BLUE_TOOTH_OPEN_CLOSE=8002;                 //蓝牙打开状态

    public static final int BLUE_TOOTH_SEACH_START=8004;                //蓝牙搜索开始
    public static final int BLUE_TOOTH_SEACH_RESULT=8005;               //蓝牙搜索返回结果
    public static final int BLUE_TOOTH_SEACH_STOP=8006;                 //蓝牙搜索停止
    public static final int BLUE_TOOTH_SEACH_CANCEL=8007;               //蓝牙搜索取消

    /**
     * 蓝牙连接状态监听
     * 成功or失败
     */
    public static final int BLUE_REGIST_CONNECT_SUCCESS=8008;
    public static final int BLUE_REGIST_CONNECT_FAILE=8009;

    public static final int BLUE_CONNECT_SUCCESS=8010;                    //连接成功
    public static final int BLUE_CONNECT_FAILE=8011;                      //连接失败

    public static final int BLUE_DATA_CONNECT_SUCCESS=8012;              //服务连接成功
    public static final int BLUE_DATA_CONNECT_FAILE=8013;                //服务连接失败
    public static final int BLUE_DATA_CONNECT_SEND=8014;                 //数据发送
    private static Handler mHandler;
    private static Context mContext;
    private String deviceType="";                              //蓝牙数据读取类型

    public BleToothKitUtil(Context context){
        mContext = context;
    }

    public void setHandler(Handler handler){
        mHandler=handler;
    }

    /**
     * 搜索设备
     */
    private List<SearchResult> mDevices;
    public void searchDevice(final String blecode){
        mDevices = new ArrayList<>();
        SearchRequest request = new SearchRequest.Builder().searchBluetoothLeDevice(5000, 2).build();
        BleClientManager.getClient(mContext).search(request, new SearchResponse() {
            @Override
            public void onSearchStarted(){
                Message mes=new Message();
                mes.what=BLUE_TOOTH_SEACH_START;
                mHandler.sendMessage(mes);
            }

            @Override
            public void onDeviceFounded(SearchResult device){
                if (!mDevices.contains(device)){
                    mDevices.add(device);
                    if(device.getAddress().equals(StringUtils.formatMac(blecode, ":"))){
                        Message mes=new Message();
                        mes.obj=blecode;
                        mes.what=BLUE_TOOTH_SEACH_RESULT;
                        mHandler.sendMessage(mes);
                    }
                }
            }

            @Override
            public void onSearchStopped() {
                mDevices.clear();
                Message mes=new Message();
                mes.what=BLUE_TOOTH_SEACH_STOP;
                mHandler.sendMessage(mes);
            }

            @Override
            public void onSearchCanceled(){
                mDevices.clear();
                Message mes=new Message();
                mes.what=BLUE_TOOTH_SEACH_CANCEL;
                mHandler.sendMessage(mes);
            }
        });
    }

    /**
     * 停止设备扫描
     */
    public void stopSeachDevice() {
        BleClientManager.getClient(mContext).stopSearch();
    }

    /**
     * 蓝牙状态判断且进行开启
     */
    public static boolean bleCheckAndListener(Activity activity){
        if (!BleClientManager.getClient(mContext).isBluetoothOpened()){
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            activity.startActivity(enableBtIntent);

            //BleClientManager.getClient(mContext).openBluetooth();
            registerBleListener();
            return false;
        }
        return true;
    }

    /**
     * 蓝牙状态判断
     */
    public boolean bleCheck(){
        return BleClientManager.getClient(mContext).isBluetoothOpened();
    }

    /**
     *蓝牙开关状态监听
     */
    public static void registerBleListener(){
        BleClientManager.getClient(mContext).registerBluetoothStateListener(bleStatuListener);
    }

    /**
     * 蓝牙状态回调
     */
    private static BluetoothStateListener bleStatuListener=new BluetoothStateListener(){
        @Override
        public void onBluetoothStateChanged(boolean openOrClosed) {
            Message mes=new Message();
            mes.obj=openOrClosed;
            mes.what=BLUE_TOOTH_OPEN_CLOSE;
            mHandler.sendMessage(mes);
        }
    };

    /**
     *解除蓝牙开关状态监听
     */
    public void unRegisterBleListener(){
        BleClientManager.getClient(mContext).unregisterBluetoothStateListener(bleStatuListener);
    }

    /**
     * 注册蓝牙配对监听
     */
    public void registerBondListener(){
        BleClientManager.getClient(mContext).registerBluetoothBondListener(mBluetoothBondListener);
    }

    /**
     * 蓝牙配对监听
     */
    private final BluetoothBondListener mBluetoothBondListener = new BluetoothBondListener() {
        @Override
        public void onBondStateChanged(String mac, int bondState) {
            // bondState = Constants.BOND_NONE, BOND_BONDING, BOND_BONDED
        }
    };

    /**
     * 解除蓝牙配对监听
     */
    public void unRegisterBondListener(){
        BleClientManager.getClient(mContext).unregisterBluetoothBondListener(mBluetoothBondListener);
    }

    /**
     * 设备连接
     *
     * @param mac
     */
    public void connectDevice(final String mac){
        BleConnectOptions options = new BleConnectOptions.Builder()
                .setConnectRetry(3)
                .setConnectTimeout(20000)
                .setServiceDiscoverRetry(3)
                .setServiceDiscoverTimeout(10000)
                .build();

        BleClientManager.getClient(mContext).connect(StringUtils.formatMac(mac, ":"), options, new BleConnectResponse() {
            @Override
            public void onResponse(int code, BleGattProfile profile){
                if(code==REQUEST_SUCCESS){
                    Message mes=new Message();
                    mes.obj=mac;
                    mes.what=BLUE_CONNECT_SUCCESS;
                    mHandler.sendMessage(mes);
                }else{
                    Message mes=new Message();
                    mes.what=BLUE_CONNECT_FAILE;
                    mHandler.sendMessage(mes);
                }
            }
        });
    }

    /**
     * 注册连接监听
     */
    public void registerConnectListener(String mac){
        BleClientManager.getClient(mContext).registerConnectStatusListener(mac, mBleConnectStatusListener);
    }

    /**
     * 解除连接监听
     */
    public void unRegisterConnectListener(String mac){
        BleClientManager.getClient(mContext).unregisterConnectStatusListener(mac, mBleConnectStatusListener);
    }

    /**
     * 连接状态监听
     */
    private BleConnectStatusListener mBleConnectStatusListener = new BleConnectStatusListener(){
        @Override
        public void onConnectStatusChanged(String mac, int status) {
            if (status == STATUS_CONNECTED){
                Message mes=new Message();
                mes.obj=mac;
                mes.what=BLUE_REGIST_CONNECT_SUCCESS;
                mHandler.sendMessage(mes);
            } else if (status == STATUS_DISCONNECTED) {
                Message mes=new Message();
                mes.obj=mac;
                mes.what=BLUE_REGIST_CONNECT_FAILE;
                mHandler.sendMessage(mes);
                unRegisterConnectListener(mac);
            }
        }
    };

    /**
     * 获取蓝牙连接状态
     * @param mac
     * @return
     */
    public int getConnectStatus(String mac){
        return BleClientManager.getClient(mContext).getConnectStatus(mac);
    }

    /**
     * 断开蓝牙连接
     * @param mac
     */
    public void disconnectBleDevice(String mac){
        BleClientManager.getClient(mContext).disconnect(mac);
    }

    /**
     * 读取数据   notify
     *
     * @param mac
     * @param service
     * @param character
     */
    public void notifyBleTooth(String mac, UUID service, UUID character, final String type){
        deviceType=type;
        BleClientManager.getClient(mContext).notify(mac, service, character,mBleNotify);
    }

    /**
     * 读取数据   indicate
     *
     * @param mac
     * @param service
     * @param character
     */
    public void indicateBleTooth(String mac, UUID service, UUID character, final String type){
        deviceType=type;
        BleClientManager.getClient(mContext).indicate(mac, service, character,mBleNotify);
    }

    /**
     * 蓝牙数据读取监听
     */
    private BleNotifyResponse mBleNotify=new BleNotifyResponse() {
        @Override
        public void onNotify(UUID service, UUID character, byte[] value){
            Bundle mBundle=new Bundle();
            mBundle.putString("type",deviceType);
            mBundle.putByteArray("byteArr",value);
            Message mes=new Message();
            mes.what=BLUE_DATA_CONNECT_SEND;
            mes.obj=mBundle;
            mHandler.sendMessage(mes);
        }

        @Override
        public void onResponse(int code){
            if (code == REQUEST_SUCCESS) {
                Message mes=new Message();
                mes.what=BLUE_DATA_CONNECT_SUCCESS;
                mHandler.sendMessage(mes);
            } else {
                Message mes=new Message();
                mes.what=BLUE_DATA_CONNECT_FAILE;
                mHandler.sendMessage(mes);
            }
        }
    };

    /**
     * 关闭notify
     * @param mac
     * @param service
     * @param character
     */
    public void closeNotifyBleTooth(String mac, UUID service, UUID character){
        BleClientManager.getClient(mContext).unnotify(mac, service, character, new BleUnnotifyResponse() {
            @Override
            public void onResponse(int code) {
                if (code == REQUEST_SUCCESS) {

                }
            }
        });
    }

    /**
     * 关闭   Indicate
     * @param mac
     * @param service
     * @param character
     */
    public void closeIndicateBleTooth(String mac, UUID service, UUID character){
        BleClientManager.getClient(mContext).unindicate(mac, service, character, new BleUnnotifyResponse() {
            @Override
            public void onResponse(int code) {
                if (code == REQUEST_SUCCESS) {

                }
            }
        });
    }
}